import logging
import time

from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

from constants.constant import USER_DATA_PATH, CHROME_BIN_PATH, CHROME_DRIVER_PATH, URL_DEVELOP, TYPE_DISC, URL_APP_MANAGEMENT
from utils.FileUtil import save_excel


def loginDevelop(appInfo, userConfig):

    service = Service(executable_path=CHROME_DRIVER_PATH)

    options = webdriver.ChromeOptions()
    options.binary_location = CHROME_BIN_PATH
    options.add_argument("--head")
    options.add_argument("--start-maximized")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--user-data-dir=" + USER_DATA_PATH)

    driver = webdriver.Chrome(service=service, options=options)

    try:
        driver.implicitly_wait(20)
        driver.get(URL_DEVELOP)

        inputForUserId = driver.find_element(By.XPATH, "//*[@class='hwid-input userAccount']")
        inputForUserId.clear()
        inputForUserId.send_keys(userConfig["user_name"])

        inputForPassword = driver.find_element(By.XPATH, "//*[@class = 'hwid-input hwid-input-pwd']")
        inputForPassword.clear()
        inputForPassword.send_keys(userConfig["user_password"])

        loginButton = driver.find_element(By.XPATH, "//span[text() = '登录']")
        loginButton.click()
        time.sleep(10)
        return driver
    except Exception:
        logging.error(appInfo.app_name + "登录devPlat失败")
        return None

def directToCashFlow(driver, appInfo):
    try:
        appServiceButton = driver.find_element(By.XPATH, "//div[text()= ' 应用服务 ']")
        appServiceButton.click()
        time.sleep(3)
    except NoSuchElementException:
        logging.error("账号类型出错：找不到应用服务板块-请检查登录账号是否错误")
        raise

    try:
        cashFlowButton = driver.find_element(By.XPATH, "//div[text()='流量变现']")
        cashFlowButton.click()
        time.sleep(8)
    except Exception:
        logging.error(appInfo.app_name + ":进入流量变现失败")

def addAdPos(driver, appInfo):
    try:
        driver.switch_to.window(driver.window_handles[-1])
        time.sleep(1)
        mediaManagerButton = driver.find_element(By.XPATH, "//li[text()= '媒体管理']")
        if not mediaManagerButton.is_displayed():
            flowManagerButton = driver.find_element(By.XPATH, "//span[text()= '流量管理']")
            flowManagerButton.click()
            time.sleep(3)
        mediaManagerButton.click()
        time.sleep(3)


        addAdButton = driver.find_element(By.XPATH, "//td[contains(., '" + appInfo.app_name + "')]/following-sibling::td//button[./span[text()= '添加展示位']]")
        addAdButton.click()

        addAdTypePos(driver, "开屏", "开屏广告", appInfo)
        addAdTypePos(driver, "横幅", "横幅广告", appInfo)
        addAdTypePos(driver, "插屏", "插屏广告", appInfo)
        addAdTypePos(driver, "激励视频", "激励视频广告", appInfo)
    except Exception:
        raise


def addAdTypePos(driver, adType, disc, appInfo):
    try:
        adButton = driver.find_element(By.XPATH, "//div[text()='" + adType + "']")
        adButton.click()

        nextStepButton = driver.find_element(By.XPATH, "//span[text()= '下一步']")
        nextStepButton.click()
        time.sleep(3)

        textDiscRadio = driver.find_element(By.XPATH, "//span[text() = '文字描述']")
        textDiscRadio.click()

        inputForDisc = driver.find_element(By.XPATH, "//input[contains(@placeholder, '请描述找到展示位所需的步骤')]")
        inputForDisc.clear()
        inputForDisc.send_keys(disc)
        time.sleep(1)

        adPreferredButton = driver.find_element(By.XPATH, "//span[text()='" + TYPE_DISC[adType] + "']")
        adPreferredButton.click()
        time.sleep(1)

        saveButton = driver.find_element(By.XPATH, "//span[text()= '保存']")
        saveButton.click()
        time.sleep(3)

        if adType == "激励广告":
            returnMyMediaButton = driver.find_element(By.XPATH, "//span[text() = '返回我的媒体']")
            returnMyMediaButton.click()
        else:
            createAnotherAdButton = driver.find_element(By.XPATH, "//span[text()= '创建另一个展示位']")
            createAnotherAdButton.click()
        logging.info(appInfo.app_name + ":创建" + adType + "广告位完成")
        time.sleep(3)
    except Exception:
        logging.error(appInfo.app_name + ":创建" + adType + "广告位失败")
        raise

def getAdPos(driver, appInfo):
    try:
        time.sleep(3)
        adPosDict = {}
        driver.switch_to.window(driver.window_handles[-1])

        posManagerButton = driver.find_element(By.XPATH, "//li[text()='展示位管理']")
        posManagerButton.click()
        time.sleep(3)

        for adType in TYPE_DISC.keys():
            adPosDict[adType] = getTypeAdPos(driver, adType, appInfo)

        appInfo.ad_id_splash_1 = adPosDict["开屏"]["adId"]
        appInfo.ad_id_banner = adPosDict["横幅"]["adId"]
        appInfo.ad_id_interstitial = adPosDict["插屏"]["adId"]
        appInfo.ad_id_reward = adPosDict["激励视频"]["adId"]
        logging.info(appInfo.app_name + ":获取广告位完成")

        save_excel(adPosDict,appInfo)
    except Exception:
        logging.error(appInfo.app_name + ":获取广告位失败")
        raise

def getTypeAdPos(driver, adType, appInfo):
    try:
        adIdXpath = "//tr[td[contains(., '" + adType + "')] and td[contains(., '" + appInfo.app_name + "')]]/td[4]//div[string-length(normalize-space(.)) > 0]"
        posInfoDiv = driver.find_element(By.XPATH, adIdXpath)
        time.sleep(1)

        adNamePath = "//span[starts-with(text(), '" + f"{appInfo.app_name}_鸿蒙原生应用_{adType}"+ "')]"
        posNameDiv = driver.find_element(By.XPATH, adNamePath)
        time.sleep(1)

        return {"adId":posInfoDiv.text, "adName":posNameDiv.text}
    except:
        raise

def addMedia(driver, appInfo):
    driver.switch_to.window(driver.window_handles[-1])
    driver.get(URL_APP_MANAGEMENT)
    time.sleep(3)

    addMediaButton = driver.find_element(By.XPATH, "//span[text()= '添加媒体']")
    addMediaButton.click()
    time.sleep(1)

    mediaTypeChooseRadio = driver.find_element(By.XPATH, "//span[text()= 'Android应用（APK）']")
    mediaTypeChooseRadio.click()
    time.sleep(1)

    harmonyOsTypeRadio = driver.find_element(By.XPATH, "//span[text()= '鸿蒙原生应用']")
    harmonyOsTypeRadio.click()
    time.sleep(1)

    inputForSearchApp = driver.find_element(By.XPATH, "//span[normalize-space()='输入关键字搜索']/parent::div/preceding-sibling::div//input")
    inputForSearchApp.clear()
    inputForSearchApp.send_keys(appInfo.app_name)
    time.sleep(3)

    chooseAppSpan = driver.find_element(By.XPATH, "//span[text()='" + f"{appInfo.app_name}({appInfo.package_name})" + "']")
    chooseAppSpan.click()
    time.sleep(3)


    inputForFinger = driver.find_element(By.CLASS_NAME,"el-input__inner")
    inputForFinger.clear()
    inputForFinger.send_keys(appInfo.fingerprint1)
    time.sleep(1)
    addFingerButton = driver.find_element(By.CLASS_NAME, 'app-sha256-form-icon')
    addFingerButton.click()

    inputForFinger = driver.find_elements(By.CLASS_NAME,"el-input__inner")[1]
    inputForFinger.clear()
    inputForFinger.send_keys(appInfo.fingerprint2)

    submitButton = driver.find_element(By.XPATH, "//span[text()= '提交 ']")
    submitButton.click()
    time.sleep(3)

    returnButton = driver.find_element(By.XPATH,"//div[text()='创建展示位']")
    returnButton.click()
    time.sleep(3)


def devPlatLogout(driver):
    try:
        driver.switch_to.default_content()

        try:
            userBox = driver.find_element(By.CLASS_NAME, "user-name")
            userBox.click()
            time.sleep(1)
            logoutButton = driver.find_element(By.XPATH, "//li[text()= '注销']")
            logoutButton.click()
        except Exception:
            userBox = driver.find_element(By.XPATH, "//nz-avatar[contains(@style, 'width: 32px') and contains(@style, 'height: 32px') and contains(@style, 'line-height: 32px')]")
            userBox.click()
            time.sleep(1)
            logoutButton = driver.find_element(By.XPATH, "//span[text() = '退出登录']")
            logoutButton.click()
        time.sleep(3)
        logging.info("注销成功")
    except Exception:
        logging.error("注销失败")
        raise

